﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using GBits.ContactUtilites;

namespace GBits.ContactManager
{
    public partial class ucContact : UserControl
    {
        private DataTable connected;
        private MyContact contact;

        public ucContact()
        {
            InitializeComponent();
            InitializeConnectionTable();
            contact = new MyContact();
        }

        public ucContact(MyContact c)
        {
            InitializeComponent();

            #region Fill out Form

            tbFName.Text = c.FirstName;
            tbMName.Text = c.MiddleName;
            tbLName.Text = c.LastName;
            tbHomePhone.Text = c.HomePhone;
            tbCellPhone.Text = c.CellPhone;
            tbWebsite.Text = c.Website;
            if (c.Favorite)
                cbFav.Checked = true;
            else cbFav.Checked = false;

            switch (c.Title)
            {
                case Title.Mr:
                    rbMr.Checked = true;
                    break;
                case Title.Mrs:
                    rbMrs.Checked = true;
                    break;
                case Title.Ms:
                    rbMs.Checked = true;
                    break;
                default:
                    rbNone.Checked = true;
                    break;
            }

            lbEmails.DataSource = c.Emails;

            //Address
            tbStreet.Text = c.Address.Street;
            tbCity.Text = c.Address.City;
            tbState.Text = c.Address.State;
            tbCode.Text = c.Address.Code;
            tbCountry.Text = c.Address.Country;
            //Organization info
            tbOrgName.Text = c.Organization.OrgName;
            tbOrgTitle.Text = c.Organization.OrgTitle;
            tbOrgDepartment.Text = c.Organization.OrgDepartment;
            tbOrgPhone.Text = c.Organization.OrgPhone;
            tbOrgWebsite.Text = c.Organization.OrgWebsite;
            tbOrgStreet.Text = c.Organization.OrgAddress.Street;
            tbOrgCity.Text = c.Organization.OrgAddress.City;
            tbOrgState.Text = c.Organization.OrgAddress.State;
            tbOrgCode.Text = c.Organization.OrgAddress.Code;
            tbOrgCountry.Text = c.Organization.OrgAddress.Country;

            //
            //TODO: deal with picture

            //Notes
            tbNotes.Text = c.Notes;

            InitializeConnectionTable();
            FillConnectionTable(c.Connected);

            #endregion

            contact = c;
        }

        public void SetContactCard(MyContact c)
        {
            #region Fill out Form

            this.tbFName.Text = c.FirstName;
            this.tbMName.Text = c.MiddleName;
            this.tbLName.Text = c.LastName;
            this.tbHomePhone.Text = c.HomePhone;
            this.tbCellPhone.Text = c.CellPhone;
            this.tbWebsite.Text = c.Website;
            if (c.Favorite)
                this.cbFav.Checked = true;
            else this.cbFav.Checked = false;

            switch (c.Title)
            {
                case Title.Mr:
                    this.rbMr.Checked = true;
                    break;
                case Title.Mrs:
                    this.rbMrs.Checked = true;
                    break;
                case Title.Ms:
                    this.rbMs.Checked = true;
                    break;
                default:
                    this.rbNone.Checked = true;
                    break;
            }

            this.lbEmails.DataSource = c.Emails;

            //Address
            this.tbStreet.Text = c.Address.Street;
            this.tbCity.Text = c.Address.City;
            this.tbState.Text = c.Address.State;
            this.tbCode.Text = c.Address.Code;
            this.tbCountry.Text = c.Address.Country;
            //Organization info
            this.tbOrgName.Text = c.Organization.OrgName;
            this.tbOrgTitle.Text = c.Organization.OrgTitle;
            this.tbOrgDepartment.Text = c.Organization.OrgDepartment;
            this.tbOrgPhone.Text = c.Organization.OrgPhone;
            this.tbOrgWebsite.Text = c.Organization.OrgWebsite;
            this.tbOrgStreet.Text = c.Organization.OrgAddress.Street;
            this.tbOrgCity.Text = c.Organization.OrgAddress.City;
            this.tbOrgState.Text = c.Organization.OrgAddress.State;
            this.tbOrgCode.Text = c.Organization.OrgAddress.Code;
            this.tbOrgCountry.Text = c.Organization.OrgAddress.Country;

            //
            //TODO: deal with picture

            //Notes
            this.tbNotes.Text = c.Notes;

            InitializeConnectionTable();
            FillConnectionTable(c.Connected);

            #endregion

            contact = c;
        }

        private void CreateConnectionTable()
        {
            connected = new DataTable();

            DataColumn col = new DataColumn();
            col.DataType = typeof(string);
            col.ColumnName = "Id";
            connected.Columns.Add(col);

            col = new DataColumn();
            col.DataType = typeof(string);
            col.ColumnName = "Name";
            connected.Columns.Add(col);

            col = new DataColumn();
            col.DataType = typeof(string);
            col.ColumnName = "Connection";
            connected.Columns.Add(col);
        }

        private void SetDataGrid()
        {
            dgvRelated.Columns["Id"].ReadOnly = true;
            dgvRelated.Columns["Id"].Visible = false;
            dgvRelated.Columns["Name"].ReadOnly = true;
            dgvRelated.Columns["Name"].Width = 200;
            dgvRelated.Columns["Connection"].ReadOnly = true;
            dgvRelated.Columns["Connection"].Width = 150;
        }

        private void BindDataGrid()
        {
            dgvRelated.DataSource = connected;
            dgvRelated.Columns[0].Visible = false;
        }

        private void InitializeConnectionTable()
        {
            CreateConnectionTable();
            BindDataGrid();
            SetDataGrid();
        }

        private void FillConnectionTable(List<Related> lst)
        {
            if (lst != null)
            {
                foreach (Related r in lst)
                {
                    DataRow dsr = connected.NewRow();
                    dsr[0] = r.Id;
                    dsr[1] = r.Name;
                    dsr[2] = r.Connection;
                    connected.Rows.Add(dsr);
                }
                BindDataGrid();
            }
        }

        private void btnRtlnAdd_Click(object sender, EventArgs e)
        {
            frmAddConnection add = new frmAddConnection();
            add.ShowDialog();
            DataRow dsr = connected.NewRow();
            dsr[0] = add.r.Id;
            dsr[1] = add.r.Name;
            dsr[2] = add.r.Connection;
            connected.Rows.Add(dsr);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbFName.Text != "" && tbMName.Text != "" && tbLName.Text != "")
            {
                if (tbOrgName.Text == "")
                    tbOrgName.Text = "Unknown";
                saveContactDialog.InitialDirectory = UserOptions.dataDirectory;
                saveContactDialog.FileName = tbFName.Text + "_" + tbMName.Text + "_" + tbLName.Text;
                saveContactDialog.ShowDialog();
                ((frmMain)this.Parent.Parent.Parent).populateTree();
            }
            else
            {
                MessageBox.Show("Contact must have a full name in order to save", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (tbEmail.Text.Trim() != "" && tbEmail.Text.Contains('@'))
            {
                lbEmails.Items.Add(tbEmail.Text);
                tbEmail.Text = "";
                tbEmail.Focus();
            }
            else
            {
                MessageBox.Show("Invalid Email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbEmail.Focus();
            }
        }

        private void lbEmails_DoubleClick(object sender, EventArgs e)
        {
            tbEmail.Text = lbEmails.Text;
        }

        private void btnGO_Click(object sender, EventArgs e)
        {
            if (tbWebsite.Text.CompareTo("http://") == 0 || tbWebsite.Text == "")
            {
                MessageBox.Show("Invalid Personal Web Address, please apply input a new personal website", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
            else
            {
                System.Diagnostics.Process.Start(tbWebsite.Text);
            }
        }

        private void btnGrpGo_Click(object sender, EventArgs e)
        {
            if (tbOrgWebsite.Text.CompareTo("http://") == 0 || tbOrgWebsite.Text == "")
            {
                MessageBox.Show("Invalid Organization Web Address, please input a new organization website", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
            else
            {
                System.Diagnostics.Process.Start(tbOrgWebsite.Text);
            }
        }

        private void btnSendEmail_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("mailto:" + lbEmails.Text);
            }
            catch
            {
                MessageBox.Show("Error opening email client", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lbEmails_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)
            {
                lbEmails.Items.Remove(lbEmails.SelectedItem);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Console.WriteLine(UserOptions.dataDirectory);
            if (contact.Id != String.Empty || contact.Id != null)
            {
                File.Delete(contact.Id);
            }
            ((frmMain)this.Parent.Parent.Parent).populateTree();
            ((frmContact)this.Parent).Close();
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            #region Get Info from Form
            contact.Id = saveContactDialog.FileName;
            contact.FirstName = tbFName.Text;
            contact.MiddleName = tbMName.Text;
            contact.LastName = tbLName.Text;
            contact.HomePhone = tbHomePhone.Text;
            contact.CellPhone = tbCellPhone.Text;
            contact.Website = tbWebsite.Text;

            if (cbFav.Checked == true)
                contact.Favorite = true;
            else contact.Favorite = false;

            if (rbMr.Checked)
                contact.Title = Title.Mr;
            else if (rbMrs.Checked)
                contact.Title = Title.Mrs;
            else if (rbMs.Checked)
                contact.Title = Title.Ms;
            else
                contact.Title = Title.None;

            List<string> lst = new List<string>();
            foreach (string s in lbEmails.Items)
            {
                lst.Add(s);
            }
            contact.Emails = lst;

            //Address
            contact.Address.Street = tbStreet.Text;
            contact.Address.City = tbCity.Text;
            contact.Address.State = tbState.Text;
            contact.Address.Code = tbCode.Text;
            contact.Address.Country = tbCountry.Text;
            //Organization info
            contact.Organization.OrgName = tbOrgName.Text;
            contact.Organization.OrgTitle = tbOrgTitle.Text;
            contact.Organization.OrgDepartment = tbOrgDepartment.Text;
            contact.Organization.OrgPhone = tbOrgPhone.Text;
            contact.Organization.OrgWebsite = tbOrgWebsite.Text;
            contact.Organization.OrgAddress.Street = tbOrgStreet.Text;
            contact.Organization.OrgAddress.City = tbOrgCity.Text;
            contact.Organization.OrgAddress.State = tbOrgState.Text;
            contact.Organization.OrgAddress.Code = tbOrgCode.Text;
            contact.Organization.OrgAddress.Country = tbOrgCountry.Text;

            //TODO: deal with picture

            //Notes
            contact.Notes = tbNotes.Text;
            //connected
            List<Related> list = new List<Related>();
            foreach (DataRow r in connected.Rows)
            {
                Related rel = new Related(r[0].ToString(), r[1].ToString(), r[2].ToString());
                list.Add(rel);
            }
            contact.Connected = list;

            if (this.Parent is frmContact)
            {
                this.Parent.Text = contact.FirstName + " " + contact.MiddleName + " " + contact.LastName;
            }
            
            //Console.WriteLine(saveContactDialog.FileName);

            DataAccess.GetData().SaveContact(contact, saveContactDialog.FileName);

            #endregion

        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            saveExportDialog.InitialDirectory = UserOptions.dataDirectory;
            saveExportDialog.FileName = tbFName.Text + "_" + tbMName.Text + "_" + tbLName.Text + "_Related Contacts";
            saveExportDialog.ShowDialog();
        }

        private void saveExportDialog_FileOk(object sender, CancelEventArgs e)
        {
            if (connected != null)
            {
                StringWriter sw = new StringWriter();
                sw.Write("#,Name,Connection" + Environment.NewLine);

                for (int i = 0; i < connected.Rows.Count; i++)
                {
                    sw.Write((i + 1).ToString() + "," + connected.Rows[i][1].ToString() + "," + connected.Rows[i][2].ToString() + Environment.NewLine);
                }
                Console.WriteLine(saveExportDialog.FileName + " : " + sw.ToString());
                string results = DataAccess.GetData().ExportFile(saveExportDialog.FileName, sw.ToString());
                if (results != "")
                {
                    MessageBox.Show(results, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void btnView_Click(object sender, EventArgs e)
        {
            if (dgvRelated.SelectedRows.Count >= 1)
            {
                //try
                //{
                    foreach (DataGridViewRow row in dgvRelated.SelectedRows)
                    {
                        frmContact frm = new frmContact(connected.Rows[row.Index][0].ToString());
                        frm.Parent = ((frmMain)this.Parent.Parent.Parent.Parent);
                        frm.Show();
                    }
                //}
                //catch
                //{
                //    MessageBox.Show("Error Opening Contact", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (dgvRelated.SelectedRows.Count >= 1)
            {
                try
                {
                    foreach (DataGridViewRow row in dgvRelated.SelectedRows)
                    {
                        connected.Rows.RemoveAt(row.Index);
                    }
                }
                catch
                {
                    MessageBox.Show("Error Removing Connection", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        

    }
}
